﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StockShark.Models;
using StockShark.ViewModels;
using System.Web.Security;

namespace StockShark.Controllers
{
    public class HomeController : Controller
    {
        StockSharkDB db = new StockSharkDB();

        public ActionResult Index()
        {
            StartPageData data = new StartPageData();
            if (Request.IsAuthenticated)
            {
                Guid userId = (Guid)Membership.GetUser().ProviderUserKey;
                data.accountList = db.BrokerageAccounts
                    .Where(r => r.UserId == userId)
                    .ToList();
                data.instrumentList = db.WatchedInstruments
                    .Where(r => r.UserId == userId)
                    .Select(r => r.Paper)
                    .OrderBy(r => r.Name)
                    .ToList();
            }
            return View(data);
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Rules()
        {
            return View();
        }

        public ActionResult Schedule()
        {
            return View();
        }

        public ActionResult Scoreboard(int page = 1)
        {
            int recordsPerPage = 10;

            if (page < 1)
                return RedirectToAction("Scoreboard", new { page = 1 });

            ViewBag.PageNo = page;
            ViewBag.RecordsPerPage = recordsPerPage;
            ViewBag.PagesTotal = (db.BrokerageAccounts.Count() - 1) / recordsPerPage + 1;

            if (page > ViewBag.PagesTotal)
                return RedirectToAction("Scoreboard", new { page = ViewBag.PagesTotal });                       
            
            var accountList = db.BrokerageAccounts
                .OrderByDescending(a => a.TotalValue)
                .Skip((page - 1) * recordsPerPage)
                .Take(recordsPerPage);
            var accountWithUserList = new List<ScoreboardData>();
            int position = (page - 1) * recordsPerPage + 1;
            foreach (var a in accountList)
            {
                accountWithUserList.Add(new ScoreboardData(a, position++));
            }

            return View(accountWithUserList);
        }

        public ActionResult Dictionary(string letter)
        {
            var fulllist = db.DictionaryEntries.OrderBy(r => r.Term);
            var letters = new HashSet<string>();
            foreach (var item in fulllist)
            {
                letters.Add(item.Term.Substring(0, 1));
            }
            var list = fulllist.Where(r => r.Term.StartsWith(letter) || letter == null);
            ViewBag.Letters = letters;
            return View(list);
        }

        [Authorize]
        public ActionResult Watch(int item, string returnUrl)
        {
            Guid userId = (Guid)Membership.GetUser().ProviderUserKey;
            int watched = db.WatchedInstruments.Where(r => r.PaperId == item && r.UserId == userId).Count();
            Instrument instr = db.Instruments.Find(item);
            if (watched == 0 && instr != null)
            {
                db.WatchedInstruments.Add(new WatchedInstrument { Paper = instr, UserId = userId });
                db.SaveChanges();
            }
            if (returnUrl != null)
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [Authorize]
        public ActionResult Unwatch(int item, string returnUrl)
        {
            Guid userId = (Guid)Membership.GetUser().ProviderUserKey;
            try
            {
                WatchedInstrument watched = db.WatchedInstruments.Single(r => r.PaperId == item && r.UserId == userId);
                db.WatchedInstruments.Remove(watched);
                db.SaveChanges();
            }
            catch (Exception e)
            { }
            if (returnUrl != null)
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
